package fr.enssat.tpcloud.service;

import java.net.URI;
import java.net.URISyntaxException;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import fr.enssat.tpcloud.dao.UserDao;
import fr.enssat.tpcloud.model.User;
import fr.enssat.tpcloud.model.UserType;

@Path("/user")
public class UserManagerService {
	
	private UserDao userDao;
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@POST
	@Path("/addUser")
	public Response postAddUser(@FormParam("login") String login, @FormParam("pwd") String pwd,
			@FormParam("email") String email) throws URISyntaxException{
		
		if(userDao.findByEmail(email) == null){
		
			User newUser = new User();
			
			newUser.setName(login);
			newUser.setPassword(pwd);
			newUser.setEmail(email);
			newUser.setType(UserType.ADMIN);
			
			userDao.save(newUser);
		}	
		return Response.temporaryRedirect(new URI("../login.html")).build();
	}
	
	
	@POST
	@Path("/isUserOk")
	public Response isUserOk(@FormParam("email") String email, @FormParam("pwd") String pwd)
			throws URISyntaxException{				
				
				Response response = Response.temporaryRedirect(new URI("../login.html")).build();
				
				User aUser = userDao.findByEmail(email);
				
				if(aUser != null && aUser.getPassword().equals(pwd))
					response = Response.temporaryRedirect(new URI("../index.html")).build();
				
				return response; 
	}
}
